<template>
  <div class="login">
    <div class="formcontainer">
      <div class="headler">
        <h1>绵绵冰全栈后台管理系统</h1>
      </div>
      <div class="main">
        <el-form
          ref="loginForm"
          :model="loginUser"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="用户名" prop="name">
            <el-input
              v-model="loginUser.name"
              type="text"
              placeholder="请输入用户名"
              autocomplete="on"
            ></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              type="password"
              placeholder="请输入密码"
              v-model="loginUser.password"
              autocomplete="on"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm(loginForm)"
              >登陆</el-button
            >
          </el-form-item>
          <div class="tiparea">
            <p>
              还没有账号？现在<router-link to="/register">注册</router-link>
            </p>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>
  
  <script setup>
import jwt_decode from "jwt-decode"; // 导入解析 JSON Web Token (JWT) 的库
import { getCurrentInstance, reactive, ref } from "vue";
import { useRouter } from "vue-router"; // 导入 Vue Router 功能
import { useStore } from "vuex"; // 导入 Vuex 功能，用于状态管理
const store = useStore(); // 创建 Vuex store 的实例
const router = useRouter(); //获取 Vue Router 的实例
const { proxy } = getCurrentInstance(); //获取当前vue实例的代理
const loginForm = ref(null);
const loginUser = reactive({
  name: "",
  password: "",
});

// 校验规则
const rules = reactive({
  name: [
    { required: true, message: "用户名不能为空", trigger: "blur" },
    { min: 2, max: 30, message: "长度在 2 到 30 个字符", trigger: "blur" },
  ],
  password: [
    { required: true, message: "密码不能为空", trigger: "blur" },
    { min: 2, max: 30, message: "长度在 2 到 30 个字符", trigger: "blur" },
  ],
});

// 登陆事件
const submitForm = (loginForm) => {
  loginForm.validate((valid) => {
    if (valid) {
      // 如果表单验证通过
      // 发送登录请求到后端
      proxy.$axios
        .post("/admin/login", loginUser)
        .then((res) => {
          // 登录成功，从响应中获取 token
          // console.log(res.data)
          const { token } = res.data;
          // 将 token 存储到 localStorage 中
          localStorage.setItem("mytoken", token);
          // 解析 token，通常使用 jwt_decode 函数
          const decoded = jwt_decode(token);
          // console.log(decoded)解析成功
          // 将 token 存储到 Vuex 中，通常用于认证用户身份
          // console.log(!isEmpty(decoded))  true
          store.dispatch("setAuthenticated", !isEmpty(decoded))// 设置用户是否认证的状态
          store.dispatch("setUser", decoded); // 设置用户信息
          // 路由跳转到主页面
          router.push("/");
        })
        .catch((err) => {
          // 处理登录失败的情况
          proxy.$message.error("登录失败！");
        });
    } else {
      // 如果表单验证未通过

      // 显示错误消息，登录表单验证失败
      proxy.$message({
        type: "error",
        message: "错误提交申请",
      });
      return false;
    }
  });
};


const isEmpty = (value) => {
  return (
    value === undefined ||
    value === null ||
    (typeof value === "object" && Object.keys(value).length === 0) ||
    (typeof value === "string" && value.trim().length === 0)
  );
};
</script>
  
  <style lang="less" scoped>
.login {
  width: 100%;
  height: 100%;
  background: url(@/assets/images/bgc.jpg);
  background-size: 100%;
  position: relative;

  .formcontainer {
    width: 370px;
    height: 250px;
    text-align: center;
    left: 35.3%;
    top: 25%;
    padding: 25px;
    position: relative;

    .headler h1 {
      font-size: large;
      text-align: center;
      font-weight: bold;
      font-size: 28px;
      margin-bottom: 20px;
    }
    .main {
      .el-button {
        width: 100%;
      }
    }
  }
}
</style>
  